<template>
	<view class="work-container">
		<uni-section title="汽车租赁合同应收单" type="line">
			<view class="example">
				<uni-forms ref="dynamicForm" label-width="400" :rules="dynamicRules" :modelValue="dynamicFormData">
					<!-- <uni-forms-item label="单据来源">
						<uni-data-select v-model="dynamicFormData.lngdatasourceid" disabled :clear="false" :localdata="dataSourceList"
							 />
					</uni-forms-item> -->
					<uni-forms-item label="单据日期">
						<uni-datetime-picker type="datetime" :clear-icon="false" v-model="dynamicFormData.strdate"
							@change="changeDate" />
					</uni-forms-item>
					<uni-forms-item label="单据号">
						<uni-easyinput v-model="dynamicFormData.strreceiptno" disabled />
					</uni-forms-item>
					<uni-forms-item v-for="(item, index) in dynamicLists" :key="item.lngreceipttypeparamid"
						:label="item.strshowname" :required="!!item.blnisnotnull" :rules="!!item.blnisnotnull?[{
							required: true,
							errorMessage: item.strshowname+'必填'
						}]:item.rules" :name="item.strcolumnname">
						<view class="form-item">
							<template v-if="item.inttype === 1">
								<uni-easyinput v-model="dynamicFormData[item.strcolumnname]"
									:placeholder="'请输入'+item.strshowname" />
							</template>
							<template v-else-if="item.inttype === 2">
								<uni-easyinput v-model="dynamicFormData[item.strcolumnname]"
									:placeholder="'请输入'+item.strshowname"
									:disabled="item.strcolumnname==='dbltotalamount'" />
							</template>
							<template v-else-if="item.inttype === 3">
								<uni-datetime-picker type="date" v-model="dynamicFormData[item.strcolumnname]"
									:start="item.start" :end="item.end" />
							</template>
							<template
								v-else-if="item.inttype === 4 || (item.inttype === 6 && item.basedropdown.bytcomponenttype===1)">
								<uni-data-select v-model="dynamicFormData[item.strcolumnname]"
									:localdata="dynamicOptions[item.lngreceipttypeparamid]" />
							</template>
							<template v-else-if="item.inttype === 6 && tem.basedropdown.bytcomponenttype!==1">
								<uni-data-picker v-model="dynamicFormData[item.strcolumnname]" placeholder="请选择"
									popup-title="请选择" />
							</template>
						</view>
					</uni-forms-item>
				</uni-forms>
			</view>
			<view class="example" v-if="detaildataList.length">
				<uni-forms v-for="(detailData,idx) in detaildataList" :key="idx" :ref="'detailForm'+idx"
					label-width="400" :modelValue="detailData" class="detail-wp">
					<uni-section :title="'明细'+(idx+1)" type="line">
						<template v-slot:right>
							<button class="mini-btn" size="mini" @click="delDetail(idx)">删除</button>
						</template>
						<uni-forms-item v-for="(item, index) in dynamicDetailLists" :key="item.lngreceipttypeparamid"
							:label="item.strshowname" :required="!!item.blnisnotnull" :rules="!!item.blnisnotnull?[{
							required: true,
							errorMessage: item.strshowname+'必填'
						}]:item.rules" :name="item.strcolumnname">
							<view class="form-item">
								<template v-if="item.inttype === 1">
									<uni-easyinput v-model="detailData[item.strcolumnname]"
										:placeholder="'请输入'+item.strshowname" />
								</template>
								<template v-else-if="item.inttype === 2">
									<uni-easyinput v-model="detailData[item.strcolumnname]"
										:placeholder="'请输入'+item.strshowname" @change="changeValue($event,item)" />
								</template>
								<template v-else-if="item.inttype === 3">
									<uni-datetime-picker type="date" v-model="detailData[item.strcolumnname]"
										:start="item.start" :end="item.end" />
								</template>
								<template
									v-else-if="item.inttype === 4 || (item.inttype === 6 && item.basedropdown.bytcomponenttype===1)">
									<uni-data-select v-model="detailData[item.strcolumnname]"
										:localdata="dynamicOptions[item.lngreceipttypeparamid]" />
								</template>
								<template v-else-if="item.inttype === 6 && tem.basedropdown.bytcomponenttype!==1">
									<uni-data-picker v-model="detailData[item.strcolumnname]" placeholder="请选择"
										popup-title="请选择" />
								</template>
							</view>
						</uni-forms-item>
					</uni-section>
				</uni-forms>
			</view>
			<view class="btn-wp">
				<button v-if="!dynamicFormData.bytstatus" class="mini-btn" type="primary" size="mini"
					@click="addDetail">添加明细</button>
			</view>
		</uni-section>
		<view class="btn-wp" style="text-align: right;">
			<button style="margin-right: 10px;" v-if="!dynamicFormData.bytstatus" class="mini-btn" type="primary" size="mini"
				@click="handleSave(0)">保存</button>
			<button style="margin-right: 10px;" v-if="!dynamicFormData.bytstatus" class="mini-btn" type="info" size="mini"
				@click="handleSave(1)">申请审批</button>
			<button
			   style="margin-right: 10px;"
				v-if="!dynamicFormData.bytstatus && lngmainid>0 && dynamicFormData.lnguserid*1===store.getters.user.userId*1"
				class="mini-btn" type="warn" size="mini" @click="del">删除单据</button>
		</view>
	</view>
</template>
<script setup>
	import {
		getCurrentInstance
	} from 'vue'
	import request from '@/utils/request'
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		getReceipttype
	} from '@/api/business/receipttype.js'
	import {
		getStrbillno
	} from '@/api/basic.js'
	import {
		addBusinessdata,
		getBusinessdata,
		delBusinessdata
	} from '@/api/business/businessdata.js'
	import {
		parseTime
	} from '@/utils/ruoyi.js'
	import store from '@/store'
	import {
		onMounted,
		reactive,
		ref
	} from "vue";
	const ins = getCurrentInstance()
	const dynamicFormData = reactive({
		lngdatasourceid: 1,
		lngbilltemplateid: 112,
		strdate: parseTime(new Date()),
		strreceiptno: '',
		bytstatus: 0,
		lngdeptid: store.getters.user.deptId,
		strparta:"石家庄多多出行科技有限公司",
		strpartaaddress:"河北省石家庄市新华区和平西路638号",
		strpartacontractname:'王炳晓 ',
		strpartatelephone:'13623319355'
	})
	const dynamicRules = reactive({})
	const lngreceipttypeid = ref(0)
	const lngmainid = ref(0)
	// const dataSourceList = ref([])
	const dynamicLists = ref([])
	const dynamicDetailLists = ref([])
	const dynamicOptions = reactive({})
    const myCtx =ref()
	// 细表list
	const detaildataList = ref([])

	function getDynamic() {
		getReceipttype(lngreceipttypeid.value).then(res => {
			if (res.code === 200) {
				dynamicLists.value = res.data.receipttypeparamList.filter(item => item.byttype === 0)
				dynamicDetailLists.value = res.data.receipttypeparamList.filter(item => item.byttype === 1)
				// 处理远程下拉数据
				getApiOptions(res)
				if (lngmainid.value) {
					findById()
				}

			}
		})
	}

	function getApiOptions(res) {
		res.data.receipttypeparamList.filter(item => item.basedropdown).forEach(item => {
			const {
				basedropdown
			} = item
			request({
				url: basedropdown.strurl,
				method: 'POST',
				data: basedropdown.strpresetparam
			}).then(rs => {
				console.log(rs)
				if (rs.code === 200) {
					if (basedropdown.bytcomponenttype === 1) {
						dynamicOptions[item.lngreceipttypeparamid] = rs.data.map(val => {
							return {
								...val,
								text: val[basedropdown.strshowcolumn],
								value: val[basedropdown.strprimarykeyname]
							}
						})
						console.log(dynamicOptions[item.lngreceipttypeparamid])
					}
				}
			})
		})
	}

	function changeDate(e) {
		getStrreceiptno()
	}

	function getStrreceiptno() {
		getStrbillno({
			lngreceipttypeid: lngreceipttypeid.value,
			strdate: dynamicFormData.strdate
		}).then(res => {
			if (res.code === 200) {
				dynamicFormData.strreceiptno = res.data
			}
		})
	}

	function addDetail() {
		if (detaildataList.value.length === 0) {
			detaildataList.value.push(reactive({}))
		} else {
			ins.refs['detailForm' + (detaildataList.value.length - 1)][0].validate().then(valid => {
				detaildataList.value.push(reactive({}))
			})
		}


	}

	function delDetail(idx) {
		detaildataList.value.splice(idx, 1)
	}

	function del() {
		delBusinessdata(lngreceipttypeid.value,lngmainid.value).then(res => {
			if (res.code === 200) {
				uni.showToast({
					title: `删除成功`
				})
				uni.navigateBack({
					delta: 1
				});
			}
		})
	}

	function findById() {
		getBusinessdata(lngreceipttypeid.value, lngmainid.value).then(res => {
			if (res.code === 200) {
				Object.assign(dynamicFormData, {
					...res.data.maindata
				})
				res.data.detaildataList.forEach(item => {
					detaildataList.value.push(item)
				})
			}
		})
	}

	function changeValue(e, item) {
		if (item.strcolumnname === "dbldetailamount") {
			let sum = 0
			detaildataList.value.forEach(val => {
				sum += isNaN(val.dbldetailamount * 1) ? 0 : val.dbldetailamount * 1
			})
			dynamicFormData.dbltotalamount = sum.toFixed(2)
		}
	}

	function handleSave(bytstatus) {
		if (detaildataList.value.length === 0) {
			uni.showToast({
				title: `请添加明细数据`
			})
			return false
		}
		ins.refs.dynamicForm.validate().then(res => {
			ins.refs['detailForm' + (detaildataList.value.length - 1)][0].validate().then(valid => {
				const intyear = new Date(dynamicFormData.strdate).getFullYear()
				const bytperiod = new Date(dynamicFormData.strdate).getMonth() + 1
				const maindata = {
					...dynamicFormData,
					"intyear": intyear,
					"bytperiod": bytperiod,
					"strdate": dynamicFormData.strdate,
					"strreceiptno": dynamicFormData.strreceiptno,
					"lngdeptid": dynamicFormData.lngdeptid,
					"dblamount": dynamicFormData.dbltotalamount,
					"bytstatus": bytstatus
				}
				const saveData = {
					"lngbilltemplateid": dynamicFormData.lngbilltemplateid,
					"lngreceipttypeid": lngreceipttypeid.value,
					"lngmainid": lngmainid.value,
					maindata: maindata,
					detaildataList: [...detaildataList.value],
					multidetailList: {}
				}
				addBusinessdata(saveData).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title: res.msg
						})
						lngmainid.value = res.lngmainid
						if (bytstatus === 1) {
							findById()
						}
					}
				})

			})
		})
	}

	onLoad((option) => {
		lngreceipttypeid.value = option.lngreceipttypeid * 1
		lngmainid.value = option.lngmainid * 1
	})
	onMounted(() => {
		getDynamic()
		if (!lngmainid.value) {
			getStrreceiptno()
		}
	})
</script>

<style lang="scss">
	/* #ifndef APP-NVUE */
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #fff;
		min-height: 100%;
		height: auto;
	}

	view {
		font-size: 14px;
		line-height: inherit;
	}

	/* #endif */

	.example {
		padding: 15px;
	}

	.btn-wp {
		padding: 15px;
	}

	.detail-wp {
		border-bottom: 1px solid #ccc;
	}
	:deep(.uni-date-x--border){
		      border: none;
		      border-bottom: 1px solid #e5e5e5;
	}
	:deep(.is-input-border){
		      border: none;
		      border-bottom: 1px solid #dcdfe6;
	}
	:deep(.uni-select){
		  border: none;
		  border-bottom: 1px solid #e5e5e5;
	}
</style>